﻿//********************************************************************************//
//创建日期：<创建日期，2016-05-06>
//创建作者：<郭登杰，朱大鹏>
//功能说明：来函公共控件-材料信息
//********************************************************************************//

using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using BLL;
using BLL.Access;
using DevExpress.Web;
using Entity;
using Web.Class;

namespace Web.Controls.LAIHAN
{
    public partial class UCLHCaiLiaoInfo : UserControl, IUCLHOperate
    {
        #region 事件

        /// <summary>
        ///     页面加载事件
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) InitControl();
            needFileBH = LaiHanLCTools.GetNeedFileBH((int) LaiHanLX);
        }

        #endregion

        #region 属性

        /// <summary>
        ///     选中项集合
        /// </summary>
        public SelectedItemCollection SelectedItems => cblCAILIAO.SelectedItems;

        /// <summary>
        ///     选中索引?
        /// </summary>
        public int SelectedIndex => cblCAILIAO.SelectedIndex;

        /// <summary>
        ///     返回列表
        /// </summary>
        public ASPxCheckBoxList CaiLiaoCheckBoxList => cblCAILIAO;

        /// <summary>
        ///     来函类型
        /// </summary>
        public eLaiHanLX LaiHanLX
        {
            get { return (eLaiHanLX) Enum.Parse(typeof(eLaiHanLX), Convert.ToString(ViewState["LaiHanLX"])); }
            set { ViewState["LaiHanLX"] = value; }
        }

        /// <summary>
        ///     必需文件编号
        /// </summary>
        private string needFileBH;

        #endregion

        #region 变量

        /// <summary>
        ///     访问数据库
        /// </summary>
        private readonly SpHelper _sphelper = new SpHelper();

        /// <summary>
        ///     上传文件信息BLL
        /// </summary>
        private readonly SYS_UPLOADProcess bllupload = new SYS_UPLOADProcess();

        private SYS_UPLOAD_LOGBLL uploadLOGBLL = new SYS_UPLOAD_LOGBLL();

        #endregion

        #region 方法

        /// <summary>
        ///     根据来函类型获取必需的文件编号
        /// </summary>
        /// <returns></returns>
        /// <summary>
        ///     配置控件
        /// </summary>
        public void InitControl()
        {
            var ds = _sphelper.P_YS_LH_LAIHANZLLB((int) LaiHanLX);
            var dt = ds.Tables[0];
            if (ds != null && ds.Tables.Count > 0)
            {
                cblCAILIAO.DataSource = dt;
                cblCAILIAO.TextField = "S_CAILIAOMC";
                cblCAILIAO.Value = "I_CAILIAOBH";
                cblCAILIAO.DataBind();
            }
        }

        /// <summary>
        ///     根据上传文件选则
        /// </summary>
        public void SelectCheckBox(string value)
        {
            foreach (ListEditItem li in cblCAILIAO.Items)
                if (value == li.Value.ToString())
                    li.Selected = true;
        }

        /// <summary>
        ///     绑定勾选列表中材料复选框
        /// </summary>
        /// <param name="yhh">用户号</param>
        /// <param name="laihanbh">来函编号</param>
        public string BindCheckBox(string yhh, string laihanbh)
        {
            var where = "";
            var indexs = "";
            if (yhh == null || yhh.Trim().Length == 0) return "";
            /*
            else
            {
                where = string.Format(" (S_YONGHUBH='{0}' and I_WENJIANLX<>" + needFileBH + ") and i_jlzt=0 ", yhh);
            }
            if (!string.IsNullOrEmpty(laihanbh))
            {
                //where = string.Format(" S_YONGHUBH='{1}' and (S_LAIHANBH='{0}' or I_WENJIANLX<>" + needFileBH + ") and i_jlzt=0 ", laihanbh, yhh);
                where = string.Format(" (S_YONGHUBH='{1}' or S_LAIHANBH='{0}') and i_jlzt=0 ", laihanbh, yhh);
            }
                 * */
            where = LaiHanLCTools.GetUserFilesCondition(yhh, laihanbh, needFileBH);
            var dt = bllupload.SelectSYS_UPLOADsDynamic(where, "", null);
            if (dt != null && dt.Rows.Count > 0)
                foreach (DataRow dr in dt.Rows)
                foreach (ListEditItem li in CaiLiaoCheckBoxList.Items)
                    if (li.Value.ToString() == dr["I_WENJIANLX"].ToString())
                    {
                        //用于后台加载绑定
                        li.Selected = true;
                        //用于前台绑定
                        indexs += li.Index + ",";
                    }

            if (indexs.Length > 0) indexs = indexs.Remove(indexs.LastIndexOf(','));
            return indexs;
        }

        /// <summary>
        ///     服务端提交时验证资料
        /// </summary>
        /// <param name="laihanbh">来函编号</param>
        /// <param name="yonghuh">用户号</param>
        public ValidateRS ValidateSubmit(string laihanbh, string yonghuh)
        {
            var rs = new ValidateRS {IsSuccess = true};
            var fileList = new List<string>();
            for (var i = 0; i < SelectedItems.Count; i++) fileList.Add(Convert.ToString(SelectedItems[i].Value));
            foreach (var fileBH in needFileBH.Split(','))
                if (!fileList.Contains(fileBH))
                {
                    rs.IsSuccess = false;
                    rs.Msg = "来函必要材料未齐全。（" + fileBH + "）";
                    break;
                }
            // 年度调整来函，（学校、医院、宾馆）用户需包含“用水分类情况表”，并且需要进行定额计算。
            if (LaiHanLX == eLaiHanLX.年度)
            {
                var drc = new YS_YG_YONGHUXXBLL().SelectYS_YG_YONGHUXXesDynamic(" I_LEIXING=0 and S_YONGHUH='" + yonghuh + "' ", null);
                string sSsdx = drc.Rows[0]["S_SHESHUIDXDM"].ToString();
                if (sSsdx.Length >= 4) sSsdx = sSsdx.Substring(0, 3);
                if ("413" == sSsdx || "414" == sSsdx || "415" == sSsdx || "416" == sSsdx || "417" == sSsdx || "406" == sSsdx || "407" == sSsdx)
                {
                    // 是否包含“用水分类情况表”
                    if (!fileList.Contains("10"))
                    {
                        rs.IsSuccess = false;
                        rs.Msg = "来函必要材料未齐全（缺少：用水分类情况表）。";
                    }
                    // 是否进行定额计算
                    else
                    {
                        bool bExists = false;
                        var ds = new BLL.SqlHelper().P_YS_DINGEJIS_SYS(yonghuh);
                        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            DataRow dr = ds.Tables[0].Rows[0];
                            bExists = Convert.ToDecimal(dr["n_l1"]) != 0;
                        }
                        if (!bExists)
                        {
                            rs.IsSuccess = false;
                            rs.Msg = "来函必要材料未齐全（缺少：定额计算表）。";
                        }
                    }
                }
            }

            /*移除数据库记录判断方式,使用控件当前选中项直接验证  by guodengjie
            string where = "";
            where = string.Format(" S_YONGHUBH='{0}' and  I_WENJIANLX={2} and S_LAIHANBH='{1}' and I_JLZT=0 ", yonghuh, laihanbh, this.needFileBH);
            DataTable dt = bllupload.SelectSYS_UPLOADsDynamic(where, "", null);
            if (dt != null && dt.Rows.Count > 0)
            {
                rs.IsSuccess = true;
                return rs;
            }
             * */
            //移除session判断方式 by guodengjie
            //if (Session["gaopai"] != null)
            //{                
            //    DataTable cailiao = Session["gaopai"] as DataTable;
            //    if (cailiao != null && cailiao.Rows.Count > 0)
            //    {
            //        foreach (DataRow dr in cailiao.Rows)
            //        {

            //            if (dr["value"].ToString() == this.needFileBH)
            //            {
            //                rs.IsSuccess = true;
            //                return rs;
            //            }
            //        }
            //    }
            //}
            if (!rs.IsSuccess && string.IsNullOrEmpty(rs.Msg))
                rs.Msg = "来函必要材料未齐全";
            return rs;
        }

        /// <summary>
        ///     更新来涵文件信息
        /// </summary>
        /// <param name="laihan">来函信息</param>
        public void SHOUJIAN(YS_LH_LAIHANXX laihan)
        {
            //string yd = BusinessTool.YS_GETSETTINGSVALUE(eSETTINGS_KEYNAME.WATER_Y_M.ToString());
            //int year = Convert.ToInt32(yd.Substring(0, 4));
            //int month = int.Parse(yd.Substring(4, 2));
            var upload = new SYS_UPLOAD();
            var count = bllupload.UpdateSYS_UPLOADsDynamic(
                "S_LAIHANBH='" + laihan.S_LAIHANBH + "',S_CAOZUOR='" + LoginInfo.CurrentUser.UserID +
                "',D_CAOZUORQ=TO_DATE('" + DateTime.Now + "','yyyy-MM-dd HH24:mi:ss'),I_TYPE=" + BusinessTool.WType,
                string.Format(" S_YONGHUBH='{0}' and I_WENJIANLX in ({1}) and S_LAIHANBH IS NULL", laihan.S_YONGHUBH,
                    needFileBH));
            /*only need update main needfile's laihanbh now,other files do not commit! comment by guodengjie 
            if (Session["gaopai"] != null)
            {
                DataTable uploadtable = Session["gaopai"] as DataTable;
                foreach (DataRow dr in uploadtable.Rows)
                {
                    upload.ID = 0;
                    ///证件类型的文件只和用户相关，更新
                    if (dr["value"].ToString() != needFileBH)
                    {
                        DataTable shangchuan = bllupload.SelectSYS_UPLOADsDynamic(string.Format(" S_YONGHUBH='{0}' and I_WENJIANLX={1} ", laihan.S_YONGHUBH,dr["value"]), "", null);
                        if (shangchuan != null && shangchuan.Rows.Count > 0)
                        {
                            upload.ID = Convert.ToInt32(shangchuan.Rows[0]["ID"]);
                        }
                    }
                    upload.S_WENJIANMC = dr["name"].ToString();
                    upload.S_WENJIANLJ = dr["path"].ToString();
                    upload.I_WENJIANLX = Convert.ToInt32(dr["value"]);
                    upload.I_SHANGCHUANLB = Convert.ToInt32(dr["type"]);
                    bllupload.InsertOrUpdate(upload);
                    SYS_UPLOAD_LOG uploadlog = new SYS_UPLOAD_LOG();
                    uploadlog.D_CAOZUORQ = DateTime.Now;
                    uploadlog.I_CAOZUOR = LoginInfo.CurrentUser.UserID;
                    uploadlog.I_JLZT = 0;
                    uploadlog.I_TYPE = 1;
                    uploadlog.I_WENJIANLX = Convert.ToInt32(dr["value"]);
                    uploadlog.ID = 0;
                    uploadlog.S_WENJIANLJ = dr["path"].ToString();
                    uploadlog.S_WENJIANMC = dr["name"].ToString();
                    uploadlog.S_YONGHUBH = laihan.S_YONGHUBH;
                    new SYS_LOGBLL().Log<SYS_UPLOAD>(LoginInfo.CurrentUser, BusinessTool.WType.ToString(), "月调整流程-月调整登记", OperateState.Modify, upload, null);
                    uploadLOGBLL.InsertOrUpdate(uploadlog);
                   
                    Session["gaopai"] = null;
                }
            }
             * */
        }

        /// <summary>
        ///     提交验证
        /// </summary>
        /// <returns></returns>
        ValidateRS IUCLHOperate.Validate()
        {
            var rs = new ValidateRS();
            rs.IsSuccess = true;
            return rs;
        }

        /// <summary>
        ///     清空材料列表勾选
        /// </summary>
        public void ClearInfo()
        {
            for (var i = 0; i < CaiLiaoCheckBoxList.Items.Count; i++) CaiLiaoCheckBoxList.Items[i].Selected = false;
        }

        /// <summary>
        ///     加载材料信息
        /// </summary>
        /// <param name="laihanxx">来函信息</param>
        public void LoadInfo(YS_LH_LAIHANXX laihanxx)
        {
            //throw new NotImplementedException();
            hdCollection.Set("lhbh", laihanxx.S_LAIHANBH);
            hdCollection.Set("yhh", laihanxx.S_YONGHUBH);
            hdCollection.Set("lhlx", Convert.ToString(laihanxx.I_LAIHANLX));
            BindCheckBox(laihanxx.S_YONGHUBH, laihanxx.S_LAIHANBH);
        }

        #endregion
    }
}